package cn.edu.zafu.bigdata.Yum;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;

public class TextFileHandler {

    public static void main(String[] args) {
        // 使用System.in创建一个BufferedReader来读取用户输入
        BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in));

        // 文件名，这里以学号为例
        String fileName = "files/202211080112.txt";

        // 用于存储用户输入的文本
        StringBuilder contentBuilder = new StringBuilder();

        System.out.println("请输入文本（单独一行输入'exit'表结束）：");

        try {
            String line;
            while (!(line = consoleReader.readLine()).equalsIgnoreCase("exit")) {
                contentBuilder.append(line).append("\n"); // 将输入的每一行添加到StringBuilder中，并添加换行符
            }

            // 写入文件
            writeToFile(fileName, contentBuilder.toString());

            // 读取文件并显示内容
            readFromFile(fileName);

        } catch (IOException e) {
            System.err.println("读取输入或写入文件时发生错误：" + e.getMessage());
        }
    }

    public static void writeToFile(String fileName, String content) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {
            writer.write(content);
            System.out.println("文本已成功写入文件：" + fileName);
        } catch (IOException e) {
            System.err.println("写入文件时发生错误：" + e.getMessage());
        }
    }

    public static void readFromFile(String fileName) {
        try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
            String line;
            System.out.println("文件内容如下：");
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            System.err.println("读取文件时发生错误：" + e.getMessage());
        }
    }
}
